<template>
  <el-upload
    class="upload-demo"
    :action="XAction"
    ref="upload"
    :headers="XHeader"
    :on-remove="ImgRemove"
    :on-success="ImgSuccess"
    :on-change="compression?handlePictureCardPreview:sss"
    :before-upload="beforeUploadImg"
    :limit="XMaxImg"
    :file-list="fileList"
    :auto-upload="compression?false:true"
    list-type="picture"
  >
    <el-button size="small" type="primary">点击上传</el-button>
    <div slot="tip" class="el-upload__tip">{{XText||'只能上传jpg/png文件，且不超过500kb'}}</div>
  </el-upload>
</template>
<script>
import { compress } from "./lib";
import axios from "axios";

export default {
  name: "upload",
  props: {
    XAction: String, //网络地址
    XHeader: Object, //请求头
    XFileList: "", //已存在图片
    XMaxImg: Number, //最大图片数量
    value: "", //忘了这个是干嘛的了别删
    XText: "", //文字提示
    maximum: "", //图片最大kb默认200
    compression: false, //开启图片压缩
  },
  data() {
    return {
      fileList: [],
      Img: [],
      list: [],
    };
  },
  destoryed() {
    this.fileList = [];
    this.Img = [];
    this.list = [];
  },
  computed: {
    newValue: {
      get: function () {
        return this.value;
      },
      set: function (value) {
        this.$emit("input", value);
      },
    },
  },
  watch: {
    value: function (newVal, oldVal) {
      if (this.value) {
        this.CoverImg(newVal);
      } else {
        this.fileList = [];
        this.Img = [];
        this.list = [];
      }
    },
  },
  mounted() {
    if (this.newValue) {
      this.CoverImg(this.newValue);
    }
  },
  methods: {
    sss() {
      return;
    },
    handlePictureCardPreview(event, file, fileList) {
      const _that = this;
      const isLt10M = event.size / 1024 / 1024 < 2;
      if (!isLt10M) {
        this.$message({
          type: "warning",
          message: "上传图片大小不能超过 5M!",
          offset: 100,
        });
        return false;
      } else {
        compress(
          event.raw,
          (val) => {
            var formDate = new FormData();
            var imgs = window.URL.createObjectURL(val);
            var file = new File([val], "img.jpg", { type: "image/jpg" });
            formDate.append("file", file);
            var axiosInstance = axios.create();
            axiosInstance({
              method: "post",
              url: this.XAction,
              headers: { ApiAuth: this.XHeader.ApiAuth },
              data: formDate,
            }).then((res) => {
              if (res.data.code === 1) {
                if (this.XMaxImg === 1) {
                  this.newValue = res.data.data.fileUrl;
                } else {
                  let obj = { type: "image", src: res.data.data.fileUrl };
                  this.Img.push(obj);
                  this.newValue = this.Img;
                }
                this.fileList.push({ name: "", url: res.data.fileUrl });
              } else {
                this.$message({
                  message: res.data.msg,
                  type: "warning",
                });
              }
            });
          },
          event.size
        );
      }
    },
    CoverImg(data) {
      this.fileList = [];
      if (this.XMaxImg === 1) {
        if (data) {
          let arr = { name: "首图", url: data };
          this.fileList.push(arr);
        }
      } else {
        let obj = {};
        if (typeof data === "string") {
          obj = JSON.parse(data);
          this.Img = JSON.parse(JSON.stringify(obj));
          for (let i in obj) {
            this.fileList.push({
              name: "第" + (parseInt(i) + 1) + "图",
              url: obj[i].src,
            });
          }
        } else if (typeof data === "object") {
          this.Img = JSON.parse(JSON.stringify(data));
          for (let i in data) {
            this.fileList.push({
              name: "第" + (parseInt(i) + 1) + "图",
              url: data[i].src,
            });
          }
        }
      }
    },
    ImgRemove(file, fileList) {
      if (this.XMaxImg === 1) {
        this.newValue = "";
      } else {
        if (fileList != 0) {
          if (file.response) {
            this.removeAaary(this.Img, file.response.data.fileUrl);
            this.newValue = JSON.stringify(this.Img);
          } else {
            this.removeAaary(this.Img, file.url);
            this.newValue = JSON.stringify(this.Img);
          }
        } else {
          this.newValue = "";
        }
      }
    },
    ImgSuccess(response, file, fileList) {
      if (this.XMaxImg === 1) {
        this.newValue = response.data.fileUrl;
      } else {
        let obj = { type: "image", src: response.data.fileUrl };
        this.Img.push(obj);
        this.newValue = this.Img;
      }

      this.fileList.push({ name: "", url: response.data.fileUrl });
    },
    removeAaary(_arr, _obj) {
      var length = _arr.length;
      for (var i = 0; i < length; i++) {
        if (_arr[i].src == _obj) {
          if (i == 0) {
            _arr.shift(); //删除并返回数组的第一个元素
            return _arr;
          } else if (i == length - 1) {
            _arr.pop(); //删除并返回数组的最后一个元素
            return _arr;
          } else {
            _arr.splice(i, 1); //删除下标为i的元素
            return _arr;
          }
        }
      }
    },
    beforeUploadImg(file) {
      const isJPG = file.type;
      if (
        isJPG != "image/jpeg" &&
        isJPG != "image/png" &&
        isJPG != "image/jpg"
      ) {
        alert("上传图片类型错误,只能是 jpeg/png/jpg 格式的图片");
        return false;
      }

      if (file.size / 1024 > (this.maximum || 200)) {
        this.$message({
          type: "warning",
          message: "“" + file.name + "”图片超过" + this.maximum || 200 + "kB",
        });
        return false;
      } else if (!/^image/.test(file.type)) {
        this.$message({
          type: "warning",
          message: "“" + file.name + "”不是图片",
        });
        return false;
      }
    },
  },
};
</script>

<style>
</style>